<template>
	<view class="profile-container">
		<uv-toast ref="toast"></uv-toast>
		<uv-modal ref="modal" :title="modalObj.title" :asyncClose="true" @confirm="confirmEdit">
			<view class="edit-form">
				<uv-input v-model="modalObj.value" :placeholder="modalObj.placeholder" :maxlength="modalObj.maxLength"
					:type="modalObj.type" />
				<text class="error-tip" v-if="modalObj.error">{{modalObj.error}}</text>
			</view>
		</uv-modal>
		<!-- 顶部用户信息卡片 -->
		<view class="user-card">
			<view class="avatar-section" @tap="changeAvatar">
				<image class="avatar" :src="userInfo.avatarUrl || '/static/avatar_man.png'" mode="aspectFill">
				</image>
				<view class="edit-badge">
					<uv-icon name="camera" size="24" color="#fff"></uv-icon>
				</view>
			</view>
			<view class="user-basic-info">
				<text class="nickname">{{userInfo.nikeName}}</text>
				<text class="status-tag" :class="{'verified': userInfo.verified}">
					{{userInfo.verified ? '已认证' : '未认证'}}
				</text>
			</view>
		</view>

		<!-- 用户资产信息 -->
		<view class="assets-card">
			<view class="asset-item">
				<text class="value">{{userInfo.points}}</text>
				<text class="label">积分</text>
			</view>
			<view class="divider"></view>
			<view class="asset-item">
				<text class="value">{{userInfo.coupon}}</text>
				<text class="label">早餐券</text>
			</view>
		</view>



		<!-- 信息编辑区域 -->
		<view class="info-edit-section">
			<view class="edit-item" @tap="showNicknameEdit">
				<text class="label">用户昵称</text>
				<view class="value-wrapper">
					<text class="value">{{userInfo.nikeName}}</text>
					<uv-icon name="arrow-right" size="16" color="#999" bold></uv-icon>
				</view>
			</view>

			<view class="edit-item disabled">
				<text class="label">手机号码</text>
				<view class="value-wrapper">
					<text class="value">{{userInfo.phone || '未绑定'}}</text>
				</view>
			</view>
		</view>

		<!-- 其他信息展示 -->
		<view class="info-display-section">
			<view class="info-item">
				<text class="label">注册时间</text>
				<text class="value">{{formatDate(userInfo.registrationDate)}}</text>
			</view>
			<view class="info-item">
				<text class="label">账号状态</text>
				<text class="value status" :class="{'active': userInfo.status === 1}">
					{{userInfo.status === 1 ? '正常' : '已禁用'}}
				</text>
			</view>
		</view>

		<!-- 商家信息卡片 -->
		<MerchantInfoEasyCard :merchantId="userInfo.registrationShop"></MerchantInfoEasyCard>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {
					id: '',
					nikeName: '',
					phone: '',
					avatarUrl: '',
					status: 1,
					registrationShop: null,
					registrationDate: null,
					openId: '',
					points: 0,
					coupon: 0,
					verified: 0
				},
				modalObj: {
					title: '',
					placeholder: '',
					value: '',
					maxLength: 50,
					type: 'text',
					error: '',
					field: ''
				},
				bindingMerchant: {}
			}
		},
		methods: {
			showToast(msg, type, duration) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			formatDate(date) {
				if (!date) return '暂无数据';
				const d = new Date(date);
				const year = d.getFullYear();
				const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
				const day = String(d.getDate()).padStart(2, '0');
				const hours = String(d.getHours()).padStart(2, '0');
				const minutes = String(d.getMinutes()).padStart(2, '0');
				return `${year}年${month}月${day}日 ${hours}时${minutes}分`;
			},
			async fetchDelImage(url) {
				try {
					const res = await this.$http.post(`/auth/image/del?url=${url}`);
				} catch (e) {
					console.error(e);
				}
			},
			async confirmEdit() {
				if (!this.validateForm()) {
					setTimeout(() => {
						this.$refs.modal.close();
					}, 1000);
					return;
				}

				try {
					const updateData = {
						[this.modalObj.field]: this.modalObj.value
					};

					const res = await this.$http.post('/auth/wechat/user/info/update', updateData);

					if (res) {
						this.showToast('更新成功', 'success', 1000);
						this.userInfo[this.modalObj.field] = this.modalObj.value;
						await this.fetchProfile();
						this.$refs.modal.close();
					}
				} catch (e) {
					this.showToast(e.msg, 'error', 1000);
				}
			},
			async fetchProfile() {
				try {
					const data = await this.$http.post('/auth/mini/profile');

					if (data) {
						this.userInfo = data;
					}
				} catch (e) {
					this.showToast('加载失败', 'error', 1000);
				}
			},
			async changeAvatar() {
				try {
					const res = await this.$http.urlImgUpload('/auth/wechat/user/avatar/upload', {
						name: 'file',
						maxSize: 1024 * 1024 * 5,
						count: 1
					});

					// 返回图片路径
					if (res) {
						this.userInfo.avatarUrl = res[0];
						this.showToast('上传成功', 'success', 1000);
					}

				} catch (e) {
					console.error(e)
					this.showToast('上传失败', 'error', 1000);
				}
			},
			showNicknameEdit() {
				this.modalObj = {
					title: '修改昵称',
					placeholder: '请输入新昵称',
					value: this.userInfo.nikeName,
					maxLength: 50,
					type: 'text',
					error: '',
					field: 'nikeName'
				};
				this.$refs.modal.open();
			},
			validateForm() {
				this.modalObj.error = '';

				if (this.modalObj.field === 'nikeName') {
					if (!this.modalObj.value.trim()) {
						this.modalObj.error = '昵称不能为空';
						return false;
					}
					if (this.modalObj.value.length > 50) {
						this.modalObj.error = '昵称不能超过50个字符';
						return false;
					}
				}

				return true;
			}
		},

		onLoad() {
			this.fetchProfile();
		}
	}
</script>

<style lang="scss" scoped>
	@import 'profile.scss';

	.info-edit-section {
		.edit-item {
			&.disabled {
				opacity: 0.6;
				pointer-events: none;
				
				.value {
					color: $mall-text-200;
				}
			}
		}
	}
</style>